package com.wtwd.device.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author zdl
 * @date 2022/8/16 16:02
 */


public class RSAUtil {
    public static String data = "12345";
    public static String ALGORITHM = "RSA";


    public static BASE64Encoder base64Encoder = new BASE64Encoder();
    public static BASE64Decoder base64Decoder = new BASE64Decoder();
    // 公钥
    private static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVSEbFe3KT+VTgCWUGD5I9iSa7rYVqU8tTKFYDPpW4v/n1gjZJeivvSN8W2azvc7yu+sUgKhByE7xCVpHT2rM9x+HIlURdaRk47L4ETTFqS+RRqlppm09UwlUuAhmSH9GnUwR58yVw2kMuA/o4k4HPG09gzf5UgiPYbgHVmf1kNwIDAQAB";
    // 私钥
    private static String privateKeyStr = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJVIRsV7cpP5VOAJZQYPkj2JJrut\n" +
            "hWpTy1MoVgM+lbi/+fWCNkl6K+9I3xbZrO9zvK76xSAqEHITvEJWkdPasz3H4ciVRF1pGTjsvgRN\n" +
            "MWpL5FGqWmmbT1TCVS4CGZIf0adTBHnzJXDaQy4D+jiTgc8bT2DN/lSCI9huAdWZ/WQ3AgMBAAEC\n" +
            "gYA1fPIurC6/qmSo6XTTGR0zA0Nnl6LoGCIQJ7G58+C9k7vCJefBqA657AhTLadzHKsMnzmmbqv5\n" +
            "0+xucIpLuF7kRfKe7V+9fL7zdb8FzdgmKU2bGDBE7emjm2QEXRy7Kn20tuthTUBAoPLhy/LtWedl\n" +
            "IwNv8QwYcfNCPmLOwcksoQJBAMXAFBGFfuD4NqezI3O6cNTL8doI+FUIwzgKTo5OwhCz5mn2ymN+\n" +
            "b9fN+4VZkhUQuGWkyFF5yrAGnJWuQnyRD/kCQQDBQVVGbPbcEb5uGBMZHGafJs3cRgxzfaaGsuyF\n" +
            "uZWnoBACGusZzpRTYKZaCFuF3mb8va97+OPC8R9Ou2+nv4GvAkBZNLjY3pvJ6K7fH9SSVDyqAgZs\n" +
            "ETfVREqscRnW4HhzCHScwJO0JklV1LnuAeYAUracQ6WJ+6MPnSvt6dpcTyQhAkBl4YGJTSyfPCN+\n" +
            "euammFhpktV4SN2LjTRbUrxqizogUrvdwD8tLcD4a72HPVyyqFr25zE6VC4OuXtd0Ga+srE1AkBx\n" +
            "f3NiBl0JSXxAd0E3V5/MlPudrEtXIHJfDz8nMhGK4TNCShf+f9y0vHMc/XwWf5HX8fIPAE3koDe1\n" +
            "77e5FJUp";

    private static RSAUtil ourInstance = new RSAUtil();

    public static RSAUtil getInstance() {
        return ourInstance;
    }

    // 生成密钥对
    private static void generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator;
        keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 获取公钥，并以base64格式打印出来
        PublicKey publicKey = keyPair.getPublic();
        publicKeyStr = new String(base64Encoder.encode(publicKey.getEncoded()));
        System.out.println("公钥："+publicKeyStr);
        // 获取私钥，并以base64格式打印出来
        PrivateKey privateKey = keyPair.getPrivate();
        privateKeyStr = new String(base64Encoder.encode(privateKey.getEncoded()));
        System.out.println("私钥："+privateKeyStr);
    }

    // 将base64编码后的公钥字符串转成PublicKey实例
    private static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = base64Decoder.decodeBuffer(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    // 将base64编码后的私钥字符串转成PrivateKey实例
    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] keyBytes = base64Decoder.decodeBuffer(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    // 公钥加密
    public static String encryptByPublicKey(String content) throws Exception {
        // 获取公钥
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipherText = cipher.doFinal(content.getBytes());
        String cipherStr = base64Encoder.encode(cipherText);
        return cipherStr;
    }

    // 私钥加密
    public static String encryptByPrivateKey(String content) throws Exception {
        // 获取私钥
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] cipherText = cipher.doFinal(content.getBytes());
        String cipherStr = base64Encoder.encode(cipherText);
        return cipherStr;
    }

    // 私钥解密
    public static String decryptByPrivateKey(String content) throws Exception {
        // 获取私钥
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] cipherText = base64Decoder.decodeBuffer(content);
        byte[] decryptText = cipher.doFinal(cipherText);
        return new String(decryptText);
    }

    // 公钥解密
    public static String decryptByPublicKey(String content) throws Exception {
        // 获取公钥
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] cipherText = base64Decoder.decodeBuffer(content);
        byte[] decryptText = cipher.doFinal(cipherText);
        return new String(decryptText);
    }


    public static void main(String[] args) throws Exception {
        // generateKeyPair();
        System.out.println("初始数据：" + data);
        // 公钥加密
        String encryptedBytes = encryptByPublicKey(data);
        System.out.println("公钥加密后：" + encryptedBytes);
        // 私钥解密
        String decryptedBytes = decryptByPrivateKey(encryptedBytes);
        System.out.println("私钥解密后：" + decryptedBytes);
        // 私钥加密
        String encryptedBytes2 = encryptByPrivateKey(data);
        System.out.println("私钥加密后：" + encryptedBytes2);
        // 公钥解密
        String decryptedBytes2 = decryptByPublicKey(encryptedBytes2);
        System.out.println("公钥解密后：" + decryptedBytes2);

    }
}



